package service

import (
	"KD_web/go/dao"
	"KD_web/go/entity"
	"KD_web/go/errors"
	"context"
	"gorm.io/gorm"
)

const api_key = "sk-555df7cd4a1d4acc9ac210c294a817fc"

func GenerateComment(comment *entity.Comment) (err error) {
	client := entity.NewTongYiClient(api_key)
	var tableEntry entity.Table
	tableId := comment.TableId
	if err := dao.SqlSession.Where("id = ?", tableId).First(&tableEntry).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.ErrTableErr
		}
		return err
	}
	// 校验是否已经存在了评论
	data := tableEntry.TableData
	var commentErr *entity.Comment
	if err := dao.SqlSession.Where("tableId = ?", tableId).First(&commentErr).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			return errors.ErrCommentAlreadyExists
		}
	}

	// 构建prompt
	initialPrompt := "我将发给你一些关于知识图谱的节点和对象的关系，请你对生成的知识图谱进行简短的总结分析,只需要200字以内一段简短的话。"
	finalPrompt := initialPrompt + "\n" + data

	ctx := context.Background()
	response, err := client.GenerateText(ctx, finalPrompt)
	if err != nil {
		return err
	}
	resComment := response.Output.Text
	comment.Comment = resComment
	if err := dao.SqlSession.Save(comment).Error; err != nil {
		return err
	}
	return nil
}

func GetCommentByTableId(tableId string) (comment *entity.Comment, err error) {
	if err := dao.SqlSession.Where("tableId = ?", tableId).Find(&comment).Error; err != nil {
		return nil, errors.ErrCommentErr
	}
	return comment, nil
}
